import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import pool from '@/lib/db';

export async function POST(request, { params }) {
  try {
    const { id } = await params;
    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }

    // 查询用户ID
    const { rows } = await pool.query('SELECT id FROM users WHERE email = $1', [session.user.email]);
    const userId = rows[0]?.id;
    if (!userId) {
      return NextResponse.json({ error: '用户不存在' }, { status: 401 });
    }

    // 检查提示词是否存在
    const checkResult = await pool.query(
      'SELECT id FROM prompts WHERE id = $1 AND user_id = $2',
      [id, userId]
    );

    if (checkResult.rows.length === 0) {
      return NextResponse.json({ error: 'Prompt not found' }, { status: 404 });
    }

    // 更新 is_public 为 true
    const result = await pool.query(
      'UPDATE prompts SET is_public = true, updated_at = $1 WHERE id = $2 AND user_id = $3',
      [new Date().toISOString(), id, userId]
    );

    if (result.rowCount === 0) {
      return NextResponse.json({ error: 'Failed to share prompt' }, { status: 500 });
    }

    return NextResponse.json({ message: 'Prompt shared successfully' });
  } catch (error) {
    console.error('Database error:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
} 